<template>
  <div>
    <van-row type="flex" justify="center" style="margin-top:80px" v-if="loading">
      <van-loading type="spinner" size="24px">加载中...</van-loading>
    </van-row>
    <van-cell title="任务 ID">{{taskId}}</van-cell>
    <van-cell title="类型" value="其它作业" />
    <van-cell title="状态">
      <van-tag v-if="this.taskInfo.state === 1">待审核</van-tag>
      <van-tag type="warning" v-else-if="this.taskInfo.state === 2">审核中</van-tag>
      <van-tag type="primary" v-else-if="this.taskInfo.state === 3">已批准</van-tag>
      <van-tag type="danger" v-else-if="this.taskInfo.state === 4">已拒绝</van-tag>
      <van-tag type="success" v-else-if="this.taskInfo.state === 5">进行中</van-tag>
      <van-tag v-else-if="this.taskInfo.state === 6">已完成</van-tag>
      <van-tag v-else-if="this.taskInfo.state === 7">已销毁</van-tag>
      <van-tag v-else>未知</van-tag>
    </van-cell>
    <van-cell title="操作" v-if="this.taskInfo.state === 3 || this.taskInfo.state === 5">
      <span v-if="this.taskInfo.state === 3">
        <van-tag type="success" @click="onClickStartTask">开始作业</van-tag>
      </span>
      <span v-else-if="this.taskInfo.state === 5">
        <!-- <van-tag type="warning" style="margin-right:32px">人工预警</van-tag> -->
        <van-tag type="danger" @click="onClickEndTask">结束作业</van-tag>
      </span>
    </van-cell>

    <!-- <van-cell title="创建人" value="张三" />
    <van-cell title="创建时间" value="2022-07-25 09:06:31" />-->
    <van-cell title="计划时间" :value="show.planedTime" />
    <van-cell title="开始时间" :value="show.beginTime" />
    <van-cell title="结束时间" :value="show.endTime" />
    <van-cell title="其它地点" :value="show.areaComment" />
    <van-cell title="其它内容" :value="taskInfo.workContent" />
    <van-cell title="我的角色" :value="show.role" />
    <van-cell title="负责人" :value="show.manager" @click="onClickRole('manager')" />
    <van-cell title="作业人员" :value="show.petrolman" @click="onClickRole('petrolman')" />
    <van-cell title="备注" :value="taskInfo.comment" />
    <van-cell title="照片/视频" />
    <van-uploader v-model="picFileList" multiple :after-read="afterRead" :deletable="false"/>
    <van-dialog v-model="showDetailDialog" :title="dialogTitle">
      <div class="roleDetail">
        <van-cell>
          <van-row>
            <van-col span="4">
              <span class="table-head">ID</span>
            </van-col>
            <van-col span="5">
              <span class="table-head">类型</span>
            </van-col>
            <van-col span="6">
              <span class="table-head">名称</span>
            </van-col>
            <van-col span="9">
              <span class="table-head">组织</span>
            </van-col>
          </van-row>
        </van-cell>
        <van-cell v-for="(item, index) in dialogData" :key="index">
          <van-row>
            <van-col span="4">
              <span class="table-content">{{getRoleDetailID(item)}}</span>
            </van-col>
            <van-col span="5">
              <span class="table-content">{{getRoleDetailType(item)}}</span>
            </van-col>
            <van-col span="6">
              <span class="table-content">{{item.name}}</span>
            </van-col>
            <van-col span="9"></van-col>
          </van-row>
        </van-cell>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
// import { getFormatDate, getFormatHourMinute } from '../utils/datetime'
import {
  getPlanTimeStr,
  getBeginEndTimeStr,
  getRoleStr,
  getRoleDetailID,
  getRoleDetailType,
  getTaskInfoRoleShow,
  fillRoleData,
  getFenceIds,
  getTaskTypeStr,
  getTaskStateStr
} from '../../utils/taskUtils'
import { putTaskOperate } from '@/api/task'
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      loading: true,
      taskId: '',
      // baseURL: 'http://152.136.13.167:9527',
      baseURL: window.location.origin,
      taskInfo: {},
      roleData: {
        manager: [],
        petrolman: []
      },
      roleName: {
        manager: '负责人',
        pertrolman: '作业人员'
      },
      show: {
        role: '',
        planedTime: '---',
        beginTime: '---',
        endTime: '---',
        manager: '',
        petrolman: '',
        areaComment: '',
        workContent: ''
      },
      memberDetail: {},
      showDetailDialog: false,
      dialogTitle: '',
      dialogData: [],
      role: -1,
      picFileList: []
    }
  },
  computed: {
    ...mapGetters(['userId', 'deviceId'])
  },
  watch: {},
  created() {
    this.taskId = this.$router.currentRoute.query.taskId
    this.role = this.$router.currentRoute.query.role
    try {
      this.getTaskInfo(this.taskId)
      this.$toast('获取任务信息成功')
    } catch (err) {
      // 对异步异常无效，await的异常怎么捕获更合理待研究
      console.log(err)
      this.loading = false
      this.$toast('获取任务信息失败')
    }
    this.getPicURL()
  },
  mounted() {
    this.sockets.subscribe('TaskChangeBriefInfo', async (channelMsg) => {
      console.log('[TASKINFO_LJ] Recv Channel TaskChangeBriefInfo')
      if (this.taskId === channelMsg.data.taskId) {
        console.log(channelMsg)
        this.loading = true
        this.getTaskInfo(this.taskId)
        const notice = `当前任务：${getTaskTypeStr(channelMsg.data.type)}(id: ${channelMsg.data.taskId}) ${getTaskStateStr(channelMsg.data.state)}！`
        this.$dialog.alert({
          message: notice
        })
      }
    })
  },
  beforeDestroy() {
    this.sockets.unsubscribe('TaskChangeBriefInfo')
  },
  methods: {
    onClickRole(role) {
      this.dialogTitle = this.roleName[role]
      this.dialogData = this.roleData[role]
      this.showDetailDialog = true
    },
    fillTaskShow(task) {
      this.show.planedTime = getPlanTimeStr(task.beginTime_plan, task.endTime_plan)
      if (this.taskInfo.beginTime) {
        this.show.beginTime = getBeginEndTimeStr(this.taskInfo.beginTime)
      }
      if (this.taskInfo.endTime) {
        this.show.endTime = getBeginEndTimeStr(this.taskInfo.endTime)
      }
      this.show.role = getRoleStr(parseInt(this.role))
      this.show.manager = getTaskInfoRoleShow(this.roleData.manager)
      this.show.petrolman = getTaskInfoRoleShow(this.roleData.petrolman)
      this.show.areaComment = task.workArea.areaComment ? task.workArea.areaComment : ''
      this.show.comment = task.comment ? task.comment : ''
    },
    async getPicURL() {
      const { data } = await this.$http.get('/pic/getImagePaths', { params: { taskId: this.taskId } })
      if (data.code === 0) {
        data.data.forEach((path) => {
          this.picFileList.push({ url: `${this.baseURL}/pic/${path}` })
        })
      }
    },
    async afterRead(e) {
      // 此时可以自行将文件上传至服务器
      e.status = 'uploading'
      e.message = '上传中...'
      const fd = new FormData()
      fd.append('deviceId', this.deviceId)
      if (this.userId) {
        fd.append('userId', this.deviceId)
      }
      fd.append('taskId', this.taskId)
      fd.append('file', e.file)
      await this.$http({
        method: 'post',
        url: '/pic/upload',
        data: fd
      })
      e.status = 'done'
    },
    async getTaskInfo(taskId) {
      const { data } = await this.$http.get('/task/taskInfo', { params: { taskId } })
      if (data.code === 0) {
        this.taskInfo = data.data
        this.taskInfo.fenceIds = getFenceIds(this.taskInfo.fences)
        this.roleData.manager = await fillRoleData(this.taskInfo.manager)
        this.roleData.petrolman = await fillRoleData(this.taskInfo.petrolman)
        this.fillTaskShow(this.taskInfo)
        this.loading = false
        console.log(this.taskInfo)
      }
    },
    async onClickStartTask() {
      const respon = await putTaskOperate(this.taskId, 'startTask', { userId: this.userId, deviceId: this.deviceId })
      if (respon.code === 0) {
        this.taskInfo.state = respon.data.state
        this.taskInfo.beginTime = respon.data.beginTime
        if (this.taskInfo.beginTime) {
          this.show.beginTime = getBeginEndTimeStr(this.taskInfo.beginTime)
        }
      }
    },
    async onClickEndTask() {
      const respon = await putTaskOperate(this.taskId, 'endTask', { userId: this.userId, deviceId: this.deviceId })
      if (respon.code === 0) {
        this.taskInfo.state = respon.data.state
        this.taskInfo.endTime = respon.data.endTime
        if (this.taskInfo.endTime) {
          this.show.endTime = getBeginEndTimeStr(this.taskInfo.endTime)
        }
      }
    },
    getRoleDetailID(item) {
      return getRoleDetailID(item)
    },
    getRoleDetailType(item) {
      return getRoleDetailType(item)
    }
  }
}
</script>

<style lang="less" scoped>
.van-cell {
  .van-cell__value {
    min-width: 70%;
  }
}

.roleDetail {
  margin: 20px;
  .table-head {
    font-weight: 700;
    font-size: 30px;
  }
  .table-content {
    font-size: 30px;
  }
  .van-cell {
    padding: 0 20px;
  }
}

.loading {
  margin: 50px;
}
</style>
